<template>
  <el-dialog
    :title="addRole.id ? '编辑角色' : '添加角色'"
    :visible="dialogVisible"
    width="500px"
    @close="closeDialog"
  >
    <template #default>
      <el-form ref="addForm" :model="addRole" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addRole.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addRole.description" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { addRoleAPI, getRoleDetailAPI, editROleAPI } from '@/api/setting'
export default {
  name: 'AddRole',
  props: {
    dialogVisible: {
      type: Boolean
    }
  },
  data() {
    return {
      addRole: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    closeDialog() {
      // 触发事件发生在子组件，修改的属性来自父组件  通过子传父
      this.$emit('close-dialog')
    },
    // 兜底验证
    confirm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          // 发送请求，获取列表，关闭弹窗，重置表单，提示用户
          if (this.addRole.id) {
            await editROleAPI(this.addRole)
          } else {
            await addRoleAPI(this.addRole)
          }
          // 通知父组件调用更新列表
          this.$emit('update-list')
          this.$message.success(`${this.addRole.id ? '修改' : '添加'}'成功`)
          this.resetForm()
        }
      })
    },
    // 点击取消执行的代码
    cancel() {
      this.resetForm()
    },
    resetForm() {
      this.closeDialog()
      this.$refs.addForm.resetFields()
      this.addRole = {
        name: '',
        description: ''
      }
    },
    async getRoleDetail(id) {
      const res = await getRoleDetailAPI(id)
      this.addRole = res
    }
  }
}
</script>
